import { getLogin, getUserInfo } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

const state = {
    token: getToken() || '',
    userInfo: {},
}

const mutations = {
    setToken(state, token) {
        state.token = token
        setToken(token)
    },
    setUserInfo(state, payload) {
        state.userInfo = payload
    },
    logout(state) {
        removeToken()
        state.token = ''
    }
}

const actions = {
    async login(context, payload) {
        const res = await getLogin(payload)
        if(res.data.success) context.commit('setToken', res.data.data)
        return res.data.success
    },
    async getUserInfo(context) {
        const res = await getUserInfo()
        context.commit('setUserInfo', res.data.data)
        return res.data.data.roles.menus
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
